document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    const clearBtn = document.getElementById('clear');
    const colorInput = document.getElementById('color');
    const lineWidthInput = document.getElementById('lineWidth');
    const lineWidthValue = document.getElementById('lineWidthValue');
    const saveBtn = document.getElementById('save');
    const undoBtn = document.getElementById('undo');
    const textInput = document.getElementById('text-input');
    const textInputContainer = document.getElementById('text-input-container');
    const textSubmitBtn = document.getElementById('text-submit');
    const textCancelBtn = document.getElementById('text-cancel');
    const fontFamilySelect = document.getElementById('fontFamily');
    const fontSizeSelect = document.getElementById('fontSize');
    
    // 获取所有工具按钮
    const toolBtns = document.querySelectorAll('.tool-btn');
    const pencilBtn = document.getElementById('pencil');
    const eraserBtn = document.getElementById('eraser');
    const textBtn = document.getElementById('text');
    const rectBtn = document.getElementById('rect');
    const circleBtn = document.getElementById('circle');
    const lineBtn = document.getElementById('line');
    const triangleBtn = document.getElementById('triangle');
    
    // 获取颜色预设
    const colorPresets = document.querySelectorAll('.color-preset');
    
    // 绘图状态
    let drawing = false;
    let currentTool = 'pencil';
    let lastX = 0;
    let lastY = 0;
    let startX = 0;
    let startY = 0;
    let textX = 0;
    let textY = 0;
    let canvasHistory = [];
    let currentStep = -1;
    let tempCanvas = null;
    
    // 设置canvas尺寸为其CSS尺寸
    function resizeCanvas() {
        const rect = canvas.getBoundingClientRect();
        canvas.width = rect.width;
        canvas.height = rect.height;
        redrawCanvas();
    }
    
    // 初始化和调整大小
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);
    
    // 保存当前状态到历史记录
    function saveState() {
        // 限制历史记录长度
        if (currentStep < canvasHistory.length - 1) {
            canvasHistory.splice(currentStep + 1);
        }
        
        currentStep++;
        canvasHistory.push(canvas.toDataURL());
        
        // 启用撤销按钮
        undoBtn.disabled = false;
    }
    
    // 创建临时画布
    function createTempCanvas() {
        tempCanvas = document.createElement('canvas');
        tempCanvas.width = canvas.width;
        tempCanvas.height = canvas.height;
        const tempCtx = tempCanvas.getContext('2d');
        tempCtx.drawImage(canvas, 0, 0);
    }
    
    // 从临时画布恢复
    function restoreFromTempCanvas() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(tempCanvas, 0, 0);
    }
    
    // 基本绘图工具
    function startDrawing(e) {
        drawing = true;
        
        const rect = canvas.getBoundingClientRect();
        
        // 获取鼠标/触摸起始位置
        if (e.type.includes('mouse')) {
            startX = lastX = e.clientX - rect.left;
            startY = lastY = e.clientY - rect.top;
        } else {
            startX = lastX = e.touches[0].clientX - rect.left;
            startY = lastY = e.touches[0].clientY - rect.top;
            e.preventDefault();
        }
        
        // 如果是形状工具，创建临时画布
        if (['rect', 'circle', 'line', 'triangle'].includes(currentTool)) {
            createTempCanvas();
        }
        
        // 如果是文字工具，显示文本输入框
        if (currentTool === 'text') {
            textX = startX;
            textY = startY;
            showTextInput(startX, startY);
            drawing = false;
        }
    }
    
    // 绘制函数
    function draw(e) {
        if (!drawing) return;
        
        const rect = canvas.getBoundingClientRect();
        let currentX, currentY;
        
        // 获取当前位置
        if (e.type.includes('mouse')) {
            currentX = e.clientX - rect.left;
            currentY = e.clientY - rect.top;
        } else {
            currentX = e.touches[0].clientX - rect.left;
            currentY = e.touches[0].clientY - rect.top;
            e.preventDefault();
        }
        
        // 根据当前工具执行绘制
        switch (currentTool) {
            case 'pencil':
                drawFreehand(currentX, currentY);
                break;
            case 'eraser':
                erase(currentX, currentY);
                break;
            case 'rect':
                drawRect(currentX, currentY);
                break;
            case 'circle':
                drawCircle(currentX, currentY);
                break;
            case 'line':
                drawLine(currentX, currentY);
                break;
            case 'triangle':
                drawTriangle(currentX, currentY);
                break;
        }
        
        // 更新最后位置
        lastX = currentX;
        lastY = currentY;
    }
    
    // 绘制自由线条
    function drawFreehand(x, y) {
        ctx.lineJoin = 'round';
        ctx.lineCap = 'round';
        ctx.strokeStyle = colorInput.value;
        ctx.lineWidth = lineWidthInput.value;
        
        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.stroke();
    }
    
    // 橡皮擦功能
    function erase(x, y) {
        ctx.lineJoin = 'round';
        ctx.lineCap = 'round';
        ctx.strokeStyle = 'white';
        ctx.lineWidth = lineWidthInput.value;
        
        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.stroke();
    }
    
    // 绘制矩形
    function drawRect(x, y) {
        // 恢复临时画布
        restoreFromTempCanvas();
        
        // 绘制新矩形
        ctx.strokeStyle = colorInput.value;
        ctx.lineWidth = lineWidthInput.value;
        ctx.beginPath();
        ctx.rect(startX, startY, x - startX, y - startY);
        ctx.stroke();
    }
    
    // 绘制圆形
    function drawCircle(x, y) {
        // 恢复临时画布
        restoreFromTempCanvas();
        
        // 计算半径
        const radius = Math.sqrt(Math.pow(x - startX, 2) + Math.pow(y - startY, 2));
        
        // 绘制新圆形
        ctx.strokeStyle = colorInput.value;
        ctx.lineWidth = lineWidthInput.value;
        ctx.beginPath();
        ctx.arc(startX, startY, radius, 0, Math.PI * 2);
        ctx.stroke();
    }
    
    // 绘制直线
    function drawLine(x, y) {
        // 恢复临时画布
        restoreFromTempCanvas();
        
        // 绘制新线条
        ctx.strokeStyle = colorInput.value;
        ctx.lineWidth = lineWidthInput.value;
        ctx.beginPath();
        ctx.moveTo(startX, startY);
        ctx.lineTo(x, y);
        ctx.stroke();
    }
    
    // 绘制三角形
    function drawTriangle(x, y) {
        // 恢复临时画布
        restoreFromTempCanvas();
        
        // 绘制新三角形
        ctx.strokeStyle = colorInput.value;
        ctx.lineWidth = lineWidthInput.value;
        ctx.beginPath();
        ctx.moveTo(startX, startY);
        ctx.lineTo(x, startY);
        ctx.lineTo((startX + x) / 2, y);
        ctx.closePath();
        ctx.stroke();
    }
    
    // 完成绘制
    function finishDrawing() {
        if (!drawing) return;
        drawing = false;
        
        // 保存当前状态
        saveState();
        
        // 清除临时画布
        tempCanvas = null;
    }
    
    // 显示文本输入框
    function showTextInput(x, y) {
        textInputContainer.style.display = 'flex';
        textInputContainer.style.left = `${x}px`;
        textInputContainer.style.top = `${y}px`;
        textInput.value = '';
        textInput.focus();
    }
    
    // 添加文字到画布
    function addTextToCanvas() {
        const text = textInput.value.trim();
        if (text) {
            ctx.font = `${fontSizeSelect.value}px ${fontFamilySelect.value}`;
            ctx.fillStyle = colorInput.value;
            ctx.fillText(text, textX, textY);
            
            // 保存状态
            saveState();
        }
        
        // 隐藏文本输入框
        textInputContainer.style.display = 'none';
    }
    
    // 撤销功能
    function undo() {
        if (currentStep > 0) {
            currentStep--;
            redrawCanvas();
        }
        
        // 如果没有更多撤销步骤，禁用按钮
        if (currentStep <= 0) {
            undoBtn.disabled = true;
        }
    }
    
    // 根据历史记录重绘画布
    function redrawCanvas() {
        if (currentStep >= 0) {
            const img = new Image();
            img.src = canvasHistory[currentStep];
            img.onload = function() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            };
        } else {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }
    }
    
    // 工具切换
    function selectTool(toolId) {
        // 移除所有工具的active类
        toolBtns.forEach(btn => btn.classList.remove('active'));
        
        // 为当前工具添加active类
        document.getElementById(toolId).classList.add('active');
        
        // 设置当前工具
        currentTool = toolId;
        
        // 根据工具设置鼠标样式
        if (currentTool === 'eraser') {
            canvas.style.cursor = 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'24\' height=\'24\' viewBox=\'0 0 24 24\'%3E%3Crect width=\'20\' height=\'20\' x=\'2\' y=\'2\' fill=\'white\' stroke=\'black\'/%3E%3C/svg%3E") 10 10, auto';
        } else if (currentTool === 'text') {
            canvas.style.cursor = 'text';
        } else {
            canvas.style.cursor = 'crosshair';
        }
    }
    
    // 清除画布
    function clearCanvas() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        saveState();
    }
    
    // 保存图片
    function saveImage() {
        const link = document.createElement('a');
        link.download = '涂鸦作品.png';
        link.href = canvas.toDataURL('image/png');
        link.click();
    }
    
    // 事件监听
    // 鼠标/触摸事件
    canvas.addEventListener('mousedown', startDrawing);
    canvas.addEventListener('touchstart', startDrawing);
    
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('touchmove', draw);
    
    window.addEventListener('mouseup', finishDrawing);
    window.addEventListener('touchend', finishDrawing);
    
    // 工具按钮事件
    pencilBtn.addEventListener('click', () => selectTool('pencil'));
    eraserBtn.addEventListener('click', () => selectTool('eraser'));
    textBtn.addEventListener('click', () => selectTool('text'));
    rectBtn.addEventListener('click', () => selectTool('rect'));
    circleBtn.addEventListener('click', () => selectTool('circle'));
    lineBtn.addEventListener('click', () => selectTool('line'));
    triangleBtn.addEventListener('click', () => selectTool('triangle'));
    
    // 文本输入事件
    textSubmitBtn.addEventListener('click', addTextToCanvas);
    textCancelBtn.addEventListener('click', () => {
        textInputContainer.style.display = 'none';
    });
    
    // 当按下Enter键时提交文本
    textInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            addTextToCanvas();
        }
    });
    
    // 颜色预设点击事件
    colorPresets.forEach(preset => {
        preset.addEventListener('click', function() {
            const color = this.getAttribute('data-color');
            colorInput.value = color;
        });
    });
    
    // 其他按钮事件
    clearBtn.addEventListener('click', clearCanvas);
    saveBtn.addEventListener('click', saveImage);
    undoBtn.addEventListener('click', undo);
    
    // 更新线宽显示
    lineWidthInput.addEventListener('input', function() {
        lineWidthValue.textContent = this.value;
    });
    
    // 初始化 - 保存空白画布状态
    saveState();
}); 